package com.plan.controller.card;

import com.plan.base.constant.BaseCode;
import com.plan.base.constant.Constant;
import com.plan.base.entity.Result;
import com.plan.controller.card.request.ExchangeLogPageListReq;
import com.plan.controller.card.request.ExchangeReq;
import com.plan.controller.card.response.ExchangeLogListRes;
import com.plan.controller.user.response.UserVO;
import com.plan.service.card.ExchangeService;
import com.plan.service.card.TeamService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 积分兑换
 *
 * @author zcl
 */
@RestController
@RequestMapping("exchange/")
public class PointExchangeController {
    @Resource
    private TeamService teamService;
    @Resource
    private ExchangeService exchangeService;

    /**
     * 积分兑换
     */
    @PostMapping(value = "exchange")
    public Result<Long> exchange(@RequestBody ExchangeReq req, HttpServletRequest httpRequest) {
        if (req.getTeamId() == null || req.getCardId() == null || req.getProductId() == null) {
            return Result.fail(BaseCode.PARAM_ERROR);
        }
        UserVO user = (UserVO) httpRequest.getAttribute(Constant.USER_KEY);
        if (!teamService.isUserInTeam(req.getTeamId(), user.getId())) {
            return Result.fail(BaseCode.ILLEGAL_OPERATION);
        }
        return exchangeService.exchange(req, user);
    }

    /**
     * 兑换记录
     */
    @PostMapping(value = "exchangeLogList")
    public Result<List<ExchangeLogListRes>> exchangeLogList(@RequestBody ExchangeLogPageListReq req, HttpServletRequest httpRequest) {
        if (req.getTeamId() == null || req.getCardId() == null) {
            return Result.fail(BaseCode.PARAM_ERROR);
        }
        if (req.getPageSize() > Constant.CLIENT_MAX_PAGE_SIZE) {
            req.setPageSize(Constant.CLIENT_MAX_PAGE_SIZE);
        }
        if (req.getPageSize() <= 0) {
            req.setPageSize(10);
        }
        UserVO user = (UserVO) httpRequest.getAttribute(Constant.USER_KEY);
        if (!teamService.isUserInTeam(req.getTeamId(), user.getId())) {
            return Result.fail(BaseCode.ILLEGAL_OPERATION);
        }
        return Result.ok(exchangeService.getExchangeLogList(req));
    }

}
